<?php

namespace App\Jobs\Train\TrainTrip;

use App\Models\Train\TrainTripInfo\Repositories\Interfaces\TrainCheckingPortRepositoryInterface;
use App\Models\Train\TrainTripInfo\Repositories\Interfaces\TrainExitingPortRepositoryInterface;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Cache;

class ProcessUpdatePort implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    private array $data;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(array $data)
    {
        $this->data = $data;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        if (!isset($this->data['train_code'])) {
            return;
        }

        /**
         * @var TrainExitingPortRepositoryInterface  $exitingPortRepo
         * @var TrainCheckingPortRepositoryInterface $checkingPortRepo
         */
        $exitingPortRepo  = app(TrainExitingPortRepositoryInterface::class);
        $checkingPortRepo = app(TrainCheckingPortRepositoryInterface::class);
        if (isset($this->data['checking_port'])) {
            $check_cache_key = "Train:CheckPort:{$this->data['train_code']}:{$this->data['from_station_code']}";
            Cache::put($check_cache_key, $this->data['checking_port'], 10 * config('trip.ttl.day'));
            $checkingPortRepo->addPort($this->data);
        }

        if (isset($this->data['exiting_port'])) {
            $exit_cache_key = "Train:ExitPort:{$this->data['train_code']}:{$this->data['to_station_code']}";
            Cache::put($exit_cache_key, $this->data['exiting_port'], 10 * config('trip.ttl.day'));
            $exitingPortRepo->addPort($this->data);
        }
    }
}
